import 'package:dio/dio.dart';
import 'package:myapp/common/store.dart';

class MyDio {

  Dio _dio = Dio();

  Dio get dio => _dio;

  set dio(Dio dio) {
    _dio = dio;
  }

  Future<T> getQuery<T>(String url, {Map<String, dynamic> params}) async {
    // 2.发送网络请求
    try {
      Response response = await dio.get(url, queryParameters: params);
      return response.data;
    } on DioError catch (e) {
      return Future.error(e);
    }
  }

  Future<T> postForm<T>(String url, {Map<String, dynamic> formData}) async {
    // 2.发送网络请求
    try {
      Response response = await dio.post(url, data: FormData.fromMap(formData));
      return response.data;
    } on DioError catch (e) {
      return Future.error(e);
    }
  }

  Future<T> uploadFile<T>(String url, String filePath, String fileName) async {
    try {
      var formData = FormData.fromMap({
        "file": await MultipartFile.fromFile(filePath, filename: fileName),
      });
      var response = await dio.post(url, data: formData);
      return response.data;
    } on DioError catch (e) {
      return Future.error(e);
    }
  }

  Future<T> postJson<T>(String url, {Map<String, dynamic> jsonData}) async {
    // 2.发送网络请求
    try {
      Response response = await dio.post(url, data: jsonData);
      return response.data;
    } on DioError catch (e) {
      return Future.error(e);
    }
  }

}
